package com.twosnail.frame.model;

import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

/**
 * Created by yangcs on 2017/7/20.
 */
public class WxUser extends Model<WxUser> {
    private Logger logger = Logger.getLogger( WxUser.class ) ;
    public static final WxUser me = new WxUser() ;

    private static final String[] CODE = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","p","q","r",
            "s","t","u","b","w","x","y","z"};
    /**
     * 获取用户
     * @param mobile
     * @return  true-->存在
     */
    public WxUser getWxUser(String mobile){
        return me.findFirst( "SELECT * FROM wx_user WHERE mobile=?" , mobile) ;
    }

    /**
     * 获取用户
     * @param userId
     * @return  true-->存在
     */
    public WxUser getWxUser(long userId){
        return me.findFirst( "SELECT * FROM wx_user WHERE wxUserId=?" , userId) ;
    }

    /**
     * 获取用户
     * @param agentCode
     * @return  true-->存在
     */
    public WxUser getWxUserByAgentCode(String agentCode){
        return me.findFirst( "SELECT * FROM wx_user WHERE agentCode=?" , agentCode) ;
    }

    /**
     * 获取登录用户下所有健身劵使用记录
     */
    public Page<Record> getAllUser(int pageNumber, int pageSize, String  keyWord){
        StringBuffer sb = new StringBuffer(" from wx_user a ");
        if( keyWord != null && !"".equals( keyWord = keyWord.trim() ) ) {
            sb.append( " where (a.mobile LIKE '%"+keyWord+"%' or a.name LIKE '%"+keyWord+"%')" ) ;
        }
        return Db.paginate(pageNumber, pageSize,
                "select a.headImg,a.mobile,a.name,a.rtDate,a.permission,a.sex,a.wxUserId " , sb.toString() );
    }

    /**
     * 更新钱包余额
     * @param wxUserId
     * @param cast
     */
    public void updateAccount(long wxUserId, BigDecimal cast){
        WxUser user = me.findFirst("select * from wx_user where wxUserId ="+wxUserId);
        if( user != null ){
            user.set("accout",user.getBigDecimal("accout") == null ? cast :(user.getBigDecimal("accout").add(cast)));
            user.update();
        }
    }

    /**
     * 代理商列表
     */
    public Page<Record> getAgents(int pageNumber, int pageSize, String  keyWord){
        StringBuffer sb = new StringBuffer(" FROM wx_user a LEFT JOIN wx_user b ON a.parentAgentCode = b.agentCode LEFT JOIN agent_level c ON a.agentLevel = c.agentLevel ");
        if( keyWord != null && !"".equals( keyWord = keyWord.trim() ) ) {
            sb.append( " where (a.mobile LIKE '%"+keyWord+"%' or a.name LIKE '%"+keyWord+"%')" ) ;
        }
        return Db.paginate(pageNumber, pageSize,
                "SELECT a.headImg,a.mobile,a.name,a.rtDate,a.permission,a.sex,a.wxUserId ,if(isnull(a.agentCode),'',a.agentCode) agentCode, if(isnull(b.name),'',b.name) parentName, c.agentLevelName, ( SELECT count(1) FROM wx_user WHERE parentAgentCode = a.agentCode ) childrens  " , sb.toString() );
    }

    /**
     * 下级代理商列表
     */
    public List<Record> getAgents(String  agentCode){
        return Db.find("SELECT a.headImg,a.mobile,a.name,a.rtDate,a.permission,a.sex,a.wxUserId ,if(isnull(a.agentCode),'',a.agentCode) agentCode, " +
                "if(isnull(b.name),'',b.name) parentName, c.agentLevelName, ( SELECT count(1) FROM wx_user WHERE parentAgentCode = a.agentCode ) childrens " +
                "FROM wx_user a LEFT JOIN wx_user b ON a.parentAgentCode = b.agentCode LEFT JOIN agent_level c ON a.agentLevel = c.agentLevel where a.parentAgentCode ='"+agentCode+"'" );
    }

    private static String getCode(){
        int a;
        StringBuffer sb = new StringBuffer();
        for (int j=0;j<5;j++){
            a = Math.abs((new Random()).nextInt(24));// 产生0~57的随机数
            sb.append(CODE[a]);
        }
        WxUser wxUser = WxUser.me.getWxUserByAgentCode(sb.toString());
        if( wxUser!=null ){
            return getCode();
        }
        return sb.toString();
    }

    /**
     * 设置代理商
     */
    public void addAgent(long userId,String agentCode){
        Db.update("UPDATE wx_user a SET a.agentCode = '"+getCode()+"',a.parentAgentCode = '"+agentCode+"',a.agentLevel = 1 where wxUserId = "+userId);
    }

    public List<Record> getAgentLevels(){
        return Db.find("SELECT * FROM agent_level ORDER BY agentLevel ASC");
    }

    /**
     * 设置代理商等级
     */
    public void updateAgentLevel(long userId,int agentLevel){
        Db.update("UPDATE wx_user a SET a.agentLevel = "+agentLevel+" where wxUserId = "+userId);
    }
}
